<template>
  <px-scrollbar>
    <div class="ele-schedule">
      <div class="op-btn-group">
        <px-button v-has="`${routerStore.getSubject}_HANDOVER_SCHEDULE_IMPORT`" type="primary" @click="handleImport">导入排班</px-button>
        &nbsp;&nbsp;
        <px-link v-has="`${routerStore.getSubject}_HANDOVER_SCHEDULE_DOWNLOAD_TEMPLATE`" underline type="primary" icon="download" @click="downloadTmp"
          >下载模板</px-link
        >
        <!-- <px-button @click="exportRecordAction">导出</px-button> -->
      </div>
      <div class="calendar-container">
        <px-calendar ref="calendar" v-model="currentDate">
          <template #header>
            <div class="canlendar-title">
              <px-button :disabled="loading" @click="selectDate('prev-month')"
                ><px-icon><ArrowLeft /></px-icon>上个月</px-button
              >
              &nbsp;
              <!-- <span>{{ date }}</span> -->
              <px-date-picker v-model="currentDate" style="width: 150px" type="month" placeholder="请选择月份" value-format="YYYY-MM-DD" clearable />
              &nbsp;
              <px-button :disabled="loading" @click="selectDate('next-month')"
                >下个月<px-icon><ArrowRight /></px-icon
              ></px-button>
              &nbsp;&nbsp;&nbsp;
              <px-button type="primary" :disabled="loading" @click="selectDate('today')">今天</px-button>
              <!-- <px-icon @click="selectDate('next-month')"><ArrowRight /></px-icon> -->
            </div>
          </template>
          <template #date-cell="{ data }">
            <div class="cell-content" :class="checkHoliday(data.day) ? 'is-holiday' : ''">
              <div class="day">{{ data.day.split("-")[2] }}<span v-if="checkHoliday(data.day)" class="holiday-tip">（休）</span></div>
              <div class="s-type">
                <div v-for="item in cellContent(data.day)" :key="item.shiftCode" class="type-item">
                  <px-popover ref="popover" placement="top-start" title="人员" :width="200" trigger="click">
                    <template #reference>
                      <div class="person">
                        <div v-for="person in item.person" :key="person.id">{{ person.name }}</div>
                        <div v-if="item.person.length > 4" class="more">
                          ... <span class="badge">{{ item.person.length - 4 }}</span>
                        </div>
                      </div>
                    </template>
                    <div class="person pop-person">
                      <div v-for="person in item.person" :key="person.id">{{ person.name }}</div>
                    </div>
                  </px-popover>
                  <div class="type">{{ item.shiftName }}({{ item.shiftCode }})</div>
                </div>
              </div>
            </div>
          </template>
        </px-calendar>
      </div>
    </div>
    <!-- 上传文件 -->
    <div v-if="fileUploadVisible">
      <FileUpload ref="uploadRef" v-model:visible="fileUploadVisible" @uploadAction="fileUploadConfirm" />
    </div>
  </px-scrollbar>
</template>

<script setup lang="ts">
import { userlistPage, queryMonthSchedule, queryMonthHoliday, importSchedule, queryShiftRule } from "@/api/handover";
import { onMounted, onUnmounted, reactive, toRefs, ref, computed, nextTick, getCurrentInstance, watchEffect } from "vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { useRouter } from "vue-router";
import { useRouterStoreHook } from "@/store/modules/router";
import FileUpload from "../components/fileUpload.vue";
import dayjs from "dayjs";

const routerStore = useRouterStoreHook();

defineOptions({
  name: "COMMON_HANDLEOVER_SCHEDULE"
});

const router = useRouter();
const calendar = ref();
const currentDate = ref(dayjs().format("YYYY-MM-DD"));
const currentMonth = ref();
const scheduleData = ref([]);
const holidayData = ref([]);
const fileUploadVisible = ref(false);
const loading = ref(false);

const downloadTmp = () => {
  let url = `${window.location.protocol}//${window.location.hostname}/download/排班模板.xlsx`;
  window.open(url);
};
const handleImport = () => {
  fileUploadVisible.value = true;
};

const fileUploadConfirm = async fileList => {
  let formData = new FormData();
  formData.append("classCode", routerStore.getSubject === "ALL" ? "" : routerStore.getSubject);
  formData.append("file", fileList[0].raw);
  const fileData = await importSchedule(formData);
  // state.closeEventFormParams.file = fileData;
  fileUploadVisible.value = false;
  PxMessage.success("上传成功");
  getScheduleData(true);
};

const selectDate = (val: InstanceType<typeof CalendarDateType>) => {
  if (!calendar.value) return;
  calendar.value.selectDate(val);
  currentDate.value = dayjs(currentDate.value).format("YYYY-MM-DD");
};

const getScheduleData = async (flag = false) => {
  const oDate = currentDate.value ? new Date(currentDate.value) : new Date();
  const oYear = oDate.getFullYear();
  const oMonth = oDate.getMonth() + 1;
  if (currentMonth.value === oMonth && !flag) {
    return;
  }
  currentMonth.value = oMonth;
  try {
    loading.value = true;
    const sdata: any = await queryMonthSchedule({
      classCode: routerStore.getSubject === "ALL" ? "" : routerStore.getSubject,
      scheduleMonth: dayjs(oDate).format("YYYY-MM")
    });
    scheduleData.value = sdata;
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
  const hdata: any = await queryMonthHoliday({ scheduleMonth: dayjs(oDate).format("YYYY-MM") });
  holidayData.value = hdata;
};
const cellContent = date => {
  let list = scheduleData.value.filter(item => item.date == date);
  if (list.length) {
    return list[0].shiftList;
  }
  return [];
};
const checkHoliday = date => {
  let list = holidayData.value.filter(item => item.holidayDate == date);
  if (list.length) {
    return true;
  }
  return false;
};
watchEffect(() => {
  getScheduleData();
});
onMounted(() => {
  // let res = await queryShiftRule({shiftGroup:""});
});
onUnmounted(() => {
  console.log("in unmount");
});
</script>
<style scoped lang="scss">
:deep(.px-select) {
  width: 100%;
}

:deep(.px-input) {
  width: 100%;
}

.ele-schedule {
  padding: 16px;
  background: #fff;

  .op-btn-group {
    position: absolute;
    top: 24px;
    right: 24px;
    text-align: right;
  }

  .calendar-container {
    .canlendar-title {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
    }
  }
}

:deep(.px-calendar-table) {
  .px-calendar-day {
    height: auto !important;
    height: 110px;
    padding: 0 !important;
    overflow: hidden;
  }

  thead th {
    background: #e7eefb;

    &:first-child {
      border-left: var(--px-calendar-border);
    }
  }
}

:deep(.px-calendar__header) {
  border-bottom: none;
}

.px-calendar-table {
  .px-calendar-day {
    padding: 0;

    .cell-content {
      position: relative;

      .day {
        position: absolute;
        top: 5px;
        left: 5px;
        z-index: 2;
        font-size: 14px;
        font-weight: bold;

        .holiday-tip {
          color: red;
        }
      }

      .s-type {
        display: flex;
        height: 110px;

        .type-item {
          position: relative;
          flex: 1;
          padding-top: 30px;
          font-size: 13px;
          text-align: center;

          .person {
            padding-left: 26px;
            font-size: 12px;
            line-height: 20px;
            text-align: left;
          }

          .type {
            position: absolute;
            top: 5px;
            right: 5px;
            font-weight: bold;
          }

          .more {
            position: absolute;
            right: 0;
            bottom: 3px;
            font-size: 14px;
            font-weight: bold;
            letter-spacing: 2px;

            .badge {
              display: inline-block;
              width: 14px;
              height: 14px;
              font-size: 12px;
              line-height: 14px;
              color: #fff;
              text-align: center;
              background: #3b82f6;
              border-radius: 14px;
            }
          }

          &:nth-child(n + 1) {
            background: #fff9e6;
          }

          &:nth-child(n + 2) {
            background: #ecf3ff;

            .type {
              color: #3b82f6;
            }
          }
        }
      }

      &.is-holiday {
        .s-type {
          background: #f5f5f5 !important;

          .type-item {
            background: #f5f5f5 !important;
          }
        }
      }
    }
  }
}

.px-popper {
  .px-popover__title {
    font-weight: bold;
  }

  .pop-person {
    line-height: 1.6;

    > div {
      position: relative;
      padding-left: 16px;

      &::before {
        position: absolute;
        top: 8px;
        left: 0;
        display: inline-block;
        width: 6px;
        height: 6px;
        content: "";
        background: #3b82f6;
        border-radius: 6px;
      }
    }
  }
}
</style>
